package feishu

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"math"
	"strconv"
	"time"
)

// Validate 验证
func Validate(signStr, timestamp, secret string) (bool, error) {
	t, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return false, err
	}

	timeGap := time.Since(time.Unix(t, 0))
	if math.Abs(timeGap.Hours()) > 1 {
		return false, fmt.Errorf("specified timestamp is expired")
	}

	ourSign := Sign(timestamp, secret)
	return ourSign == signStr, nil
}

// Sign 签名
func Sign(timestamp string, secret string) string {
	stringToSign := timestamp + "\n" + secret
	h := hmac.New(sha256.New, []byte(stringToSign))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
